
from PyQt5.QtWidgets import QMessageBox
import Utils
from Data import *
import re

def build(url, gameKey, gameSecret,apptoken,u3dVer,sdkVer,complete_callback):
    if not Utils.hasPath(f'{url}/launcher'):
        QMessageBox.question(None, '错误提醒！！', '1.请先在Unity中构建安卓原生后再导入\n2.请确认您的项目是否为Unity2019.x版本',QMessageBox.Yes)
        if complete_callback:
            complete_callback(False)
        return

    # launcher/build.gradle
    launcher_build_gradle_file = f'{url}/launcher/build.gradle'
    lbgContent = Utils.readFile(launcher_build_gradle_file)

    result = re.findall(r'compileSdkVersion [0-9][0-9]',lbgContent)
    lbgContent = re.sub(result[0], f'compileSdkVersion {sdkVer}', lbgContent,1)

    result = re.findall(r'targetSdkVersion [0-9][0-9]',lbgContent)
    lbgContent = re.sub(result[0], f'targetSdkVersion {sdkVer}', lbgContent,1)

    index = lbgContent.index("ndk {")
    endIndex = lbgContent.find("}",index)
    ndkContent = lbgContent[index:endIndex+1]
    google_play_ndk = '''ndk {
            abiFilters 'armeabi-v7a', 'arm64-v8a',"x86_64"
        }'''
    lbgContent = lbgContent.replace(ndkContent,google_play_ndk,1)
    Utils.writeInFile(launcher_build_gradle_file,lbgContent)

    # unityLibrary/proguard-unity.txt
    pgtUrl = f'{url}/unityLibrary/proguard-unity.txt'
    pgtContent = Utils.readFile(pgtUrl)
    if pgtContent.find('com.adjust.sdk') == -1:
        pgtContent = pgtContent.replace('-keep class com.google.androidgamesdk.SwappyDisplayManager { *; }','-keep class com.google.androidgamesdk.SwappyDisplayManager { *; }\n-keep class com.adjust.sdk.**{ *; }\n-keep public class com.android.installreferrer.** { *; }',1)
        Utils.writeInFile(pgtUrl,pgtContent)

    # unityLibrary/libs
    libsUrl = f'{url}/unityLibrary/libs'
    Utils.makePath(libsUrl)
    if Utils.hasPath( libsUrl ):
        if not Utils.hasPath( f'{libsUrl}/gameanalytics.aar' ):
            Utils.CopyFile('./pkt/gameanalytics.aar', f'{libsUrl}/gameanalytics.aar')
        if not Utils.hasPath( f'{libsUrl}/gameanalytics-imei.jar' ):
            Utils.CopyFile('./pkt/gameanalytics-imei.jar', f'{libsUrl}/gameanalytics-imei.jar')

    # unityLibrary/build.gradle
    ulbFile = f'{url}/unityLibrary/build.gradle'
    ulbContent = Utils.readFile(ulbFile)
    sdkContent = """
    implementation(name: 'gameanalytics', ext:'aar')
    implementation files('libs\\\gameanalytics-imei.jar')
    implementation 'com.adjust.sdk:adjust-android:4.28.6'
    implementation 'com.android.installreferrer:installreferrer:2.2'
    """
    if ulbContent.find('com.adjust.sdk') == -1:
        ulbContent = ulbContent.replace("implementation fileTree(dir: 'libs', include: ['*.jar'])", f"implementation fileTree(dir: 'libs', include: ['*.jar']){sdkContent}",1)
    
    result = re.findall(r'compileSdkVersion [0-9][0-9]',ulbContent)
    ulbContent = re.sub(result[0], f'compileSdkVersion {sdkVer}', ulbContent,1)

    result = re.findall(r'targetSdkVersion [0-9][0-9]',ulbContent)
    ulbContent = re.sub(result[0], f'targetSdkVersion {sdkVer}', ulbContent,1)

    index = ulbContent.index("ndk {")
    endIndex = ulbContent.find("}",index)
    ndkContent = ulbContent[index:endIndex+1]
    google_play_ndk = '''ndk {
            abiFilters 'armeabi-v7a', 'arm64-v8a',"x86_64"
        }'''
    ulbContent = ulbContent.replace(ndkContent,google_play_ndk,1)

    Utils.writeInFile(ulbFile,ulbContent)


    # unityLibrary/src/main/java/com/unity3d/player/UnityPlayerActivity.java
    ulaFile = f'{url}/unityLibrary/src/main/java/com/unity3d/player/UnityPlayerActivity.java'
    ulaContent = Utils.readFile(ulaFile)
    if ulaContent.find('com.adjust.sdk.AdjustEvent;') == -1:
        ulaContent = ulaContent.replace("import android.util.Log;","",1)
        ulaContent = ulaContent.replace("import android.content.pm.PackageInfo;","",1)
        ulaContent = ulaContent.replace("import android.content.pm.PackageManager;","",1)
        ulaContent = ulaContent.replace("import java.util.Timer;","",1)
        ulaContent = ulaContent.replace("import java.util.TimerTask;","",1)
        ulaContent = ulaContent.replace("import java.util.Arrays;","",1)
        ulaContent = ulaContent.replace("import java.util.ArrayList;","",1)
        ulaContent = ulaContent.replace("import java.security.NoSuchAlgorithmException;","",1)
        ulaContent = ulaContent.replace("import java.security.MessageDigest;","",1)

        impLibContent = """import android.os.Process;
import com.adjust.sdk.AdjustEvent;
import com.gameanalytics.sdk.GameAnalytics;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import com.adjust.sdk.Adjust;
import com.adjust.sdk.AdjustConfig;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import android.content.pm.Signature;
import android.util.Base64;
"""
        
        ulaContent = ulaContent.replace('import android.os.Process;',impLibContent,1)
        ulaContent = ulaContent.replace('mUnityPlayer.pause();',"mUnityPlayer.pause();\n\t\tAdjust.onPause();",1)
        ulaContent = ulaContent.replace('mUnityPlayer.resume();',"mUnityPlayer.resume();\n\t\tAdjust.onResume();",1)
        ulaContent = ulaContent.replace('mUnityPlayer.requestFocus();',"""mUnityPlayer.requestFocus();

        //Init GA
        GAInit();

        //Init Adjust
        AdjustInit();

        //获取facebook Hash key的方法
        //facebookHashKey();
        """,1)
        initSDKContent = """   
    private void facebookHashKey() {
        PackageInfo info = null;
        try {
            info = getPackageManager().getPackageInfo("com.hg.territorywar", PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public static final String ADJUST_TAG = "ADJUST";
    //Adjust Init
    public void AdjustInit(){

        String appToken = "%s";
        String environment = AdjustConfig.ENVIRONMENT_PRODUCTION;  //AdjustConfig.ENVIRONMENT_SANDBOX;  AdjustConfig.ENVIRONMENT_PRODUCTION;
        AdjustConfig config = new AdjustConfig(this, appToken, environment);
        Adjust.onCreate(config);
    }

    public void AdjustEvent(String event, String Key, String Value){

        AdjustEvent adjustEvent = new AdjustEvent(event);

        Adjust.trackEvent(adjustEvent);

        Log.d(ADJUST_TAG,event);
    }

    public void GA2AdjustEvent( String gaEvent ){

        try {

            String[] events = gaEvent.split(":");
            AdjustEvent(events[0], events[1], events[2]);
        }
        catch (Exception e) {

            e.printStackTrace();
        }
    }



    //GA Log Tag
    public  static final String GA_TAG = "GA";
    //GA Init
    public void GAInit()
    {
        String gameKey = "%s";
        String gameSecret = "%s";

        PackageManager pm = getPackageManager();
        PackageInfo info = null;
        try {
            info = pm.getPackageInfo(getPackageName(), 0);
            GameAnalytics.configureBuild(info.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        GameAnalytics.initializeWithGameKey(this, gameKey, gameSecret);
    }

    Timer ga_timer = null;
    //GA Event Dispatch
    public void GAEvent(String[] args)
    {
        try {

            //Join Params
            String buffer = "";
            for(int i =0;i<args.length;i++){

                buffer += args[i];

            }

            //分割所有事件
            String[] events = buffer.split(";");

            //后续不执行
            if(events.length < 1) return;

            //立即执行
            if( events.length == 1){

                Log.d(GA_TAG,events[0]);
                GameAnalytics.addDesignEventWithEventId(events[0]);

                //GA事件转Adjust事件
                GA2AdjustEvent(events[0]);
                return;
            }

            //清空事件列表
            if( ga_index!=0&&ga_index>=ga_events.size() ){
                ga_index = 0;
                ga_events.clear();
            }

            //追加后续发送事件
            ArrayList<String> list = new ArrayList<String>(Arrays.asList(events));
            ga_events.addAll(list);

            //开始事件迭代
            if( null == ga_timer ) {
                ga_index = 0;
                ga_timer = new Timer();
                ga_timer.schedule(new TimerTask() {
                    public void run() {
                        GAEventOnce();
                    }
                },0, 200);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    int ga_index = 0;
    ArrayList<String> ga_events = new ArrayList<String>();
    public void GAEventOnce(){

        if( ga_events == null || ga_index >= ga_events.size() )
        {
            ga_timer.cancel();
            ga_timer = null;
            Log.d(GA_TAG,"Stop Timer ... ...");
        }
        else{

            String gaEvent = ga_events.get(ga_index);

            Log.d(GA_TAG,gaEvent);

            GameAnalytics.addDesignEventWithEventId(gaEvent);

            //GA事件转Adjust事件
            GA2AdjustEvent(gaEvent);

            ga_index++;
        }

    }


// When Unity player unloaded move task to background""" % (apptoken,gameKey,gameSecret)
        ulaContent = ulaContent.replace('// When Unity player unloaded move task to background',initSDKContent,1)
    else:
        ulaContent = re.sub(r'String gameKey = ".*";', 'String gameKey = "%s";' % gameKey, ulaContent)
        ulaContent = re.sub(r'String gameSecret = ".*";', 'String gameSecret = "%s";' % gameSecret, ulaContent)
        ulaContent = re.sub(r'String appToken = ".*";', 'String appToken = "%s";' % apptoken, ulaContent)
    Utils.writeInFile(ulaFile,ulaContent)
    
    if complete_callback != None:
        complete_callback()
